package com.job.config.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.job.common.Constant;
import com.job.mapper.*;
import com.job.mapper.es.StudentInfoRepository;
import com.job.pojo.*;
import joptsimple.internal.Strings;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

@Configuration
@EnableScheduling
public class SaveElasticSearchData implements Constant {

    @Resource
    private StudentInfoRepository studentInfoRepository;

    @Resource
    private ProductInfoMapper productInfoMapper;

    @Resource
    private WorkInfoMapper workInfoMapper;

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private OwnMapper ownMapper;

    @Resource
    private CertificateMapper certificateMapper;

    private static final HashMap<Integer,String> xlMap = new HashMap<Integer,String>(){{
        put(0,"大专");
        put(1,"本科");
        put(2,"研究生");
        put(3,"博士");
    }};

    @Scheduled(fixedRate = TASKRATE)
    private void save() throws ParseException {
        ArrayList<StudentInfoPO> studentInfoPOS = new ArrayList<>();
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<Student>().apply(
                "date_format (create_time,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')"
                , perTime());

        List<Student> studentList = studentMapper.selectList(wrapper);
        studentList.forEach(student -> {
            List<Product> products = productInfoMapper.selectList(new LambdaQueryWrapper<Product>()
                    .eq(Product::getStudentId, student.getStudentId()));
            List<WorkInfo> workInfos = workInfoMapper.selectList(new LambdaQueryWrapper<WorkInfo>()
                    .eq(WorkInfo::getStudentId, student.getStudentId()));
            List<Own> owns = ownMapper.selectList(new LambdaQueryWrapper<Own>()
                    .eq(Own::getStudent_id, student.getStudentId()));
            studentInfoPOS.add(studentInfoPOConverter(student, workInfos, products,owns));
        });

        studentInfoPOS.forEach(studentInfoPO -> {
            studentInfoRepository.save(studentInfoPO);
        });
    }

    private StudentInfoPO studentInfoPOConverter(Student student, List<WorkInfo> workInfos, List<Product> products
            , List<Own> owns){
        StudentInfoPO studentInfoPO = new StudentInfoPO();
        StringBuilder productStringBuilder = new StringBuilder();
        StringBuilder workInfoStringBuilder = new StringBuilder();
        StringBuilder certificateStringBuilder = new StringBuilder();

        List<Integer> certificateIds = owns.stream().map(own -> own.getCertificateId()).collect(Collectors.toList());
        List<Certificate> certificates = certificateMapper.selectList(new LambdaQueryWrapper<Certificate>()
                .in(Certificate::getCertificateId, certificateIds));
        certificates.forEach(certificate ->
                certificateStringBuilder.append(certificate.getCertificate()).append(SEPARATE));
        workInfos.forEach(workInfo -> workInfoStringBuilder.append(workInfo.getContext()));
        products.forEach(product -> productStringBuilder.append(product.getContext()));

        studentInfoPO.setCertificate(certificateStringBuilder.toString());
        studentInfoPO.setWorkInfo(CollectionUtils.isEmpty(workInfos) ? Strings.EMPTY
                : workInfoStringBuilder.toString());
        studentInfoPO.setProductInfo(CollectionUtils.isEmpty(products) ? Strings.EMPTY
                :productStringBuilder.toString());
        studentInfoPO.setStudentId(student.getStudentId());
        studentInfoPO.setXl(xlMap.get(student.getXl()));
        studentInfoPO.setMajor(student.getMajor());
        return studentInfoPO;
    }

    //获取七天前的时间
    private LocalDateTime perTime() throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        Calendar calendar = Calendar.getInstance();
        //获取到前7天的日期
        calendar.set(Calendar.DAY_OF_YEAR,calendar.get(Calendar.DAY_OF_YEAR) - TASKRATEBYDAY);
        String today = simpleDateFormat.format(calendar.getTime());
        Date newDate = simpleDateFormat.parse(today);
        //date转localDate
        Instant instant = newDate.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = instant.atZone(zoneId).toLocalDate();
        return LocalDateTime.of(localDate, LocalTime.MIN);
    }
}
